package com.kingviker.example.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class NioServer {

    private static Map<String, SocketChannel> clientMap = new HashMap<>();

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8899));
//        ServerSocket serversocket = serverSocketChannel.socket();
//        serversocket.bind(new InetSocketAddress(8899));

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                selectionKeys.forEach(selectionKey -> {
                    final SocketChannel client;
                    try {
                        if (selectionKey.isAcceptable()) {
                            ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) selectionKey.channel();

                            client = serverSocketChannel1.accept();
                            client.configureBlocking(false);
                            client.register(selector, SelectionKey.OP_READ);
                            String key = "[" + UUID.randomUUID().toString() + "]";
                            clientMap.put(key, client);

                        } else if (selectionKey.isReadable()) {
                            client = (SocketChannel) selectionKey.channel();
                            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                            readBuffer.clear();
                            int count = client.read(readBuffer);
                            if (count > 0) {
                                readBuffer.flip();
                                Charset charset = Charset.forName("UTF-8");
                                String receiveMessage = String.valueOf(charset.decode(readBuffer).array());

                                String clientkey = null;
                                for (String key : clientMap.keySet()) {
                                    if (clientMap.get(key).equals(client)) {
                                        clientkey = key;
                                        break;
                                    }
                                }
                                String finalClientkey = clientkey;
                                clientMap.keySet().forEach(key -> {
                                    SocketChannel socketChannel = clientMap.get(key);
                                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                                    byteBuffer.put((finalClientkey + ":" + receiveMessage).getBytes());
                                    byteBuffer.flip();
                                    try {
                                        socketChannel.write(byteBuffer);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });

                                System.out.println(client + ":" + receiveMessage);
                            }
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
                selectionKeys.clear();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
